package sender;
import javax.jms.*;

import org.saxion.aktiehuis.model.BesteldProduct;
import org.saxion.aktiehuis.model.Bestelling;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;



public class BestellingSender {
	
	private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
	private String subject = "bestelling";

	private Bestelling bestelling;


	
	public BestellingSender(Bestelling bestelling){
		this.bestelling = bestelling;
	}
	
	public void setBestelling(Bestelling bestelling)
	{
		this.bestelling = bestelling;
	}
	
	public void verstuurBestelling()
	{
		System.out.println("Bestelling versturen..");
        ConnectionFactory connectionFactory =  new ActiveMQConnectionFactory(url);
            Connection connection = null;
            Session session ;
			try {
				connection = connectionFactory.createConnection();
				connection.start();

				session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

                Destination destination = session.createQueue(subject);

                MessageProducer producer = session.createProducer(destination);

			
            
            	for(BesteldProduct besteldProduct : bestelling.getProducten())
        		{
            		ProductBestelling b = new ProductBestelling(bestelling.getId(),
            				besteldProduct.getProduct().getNaam(), 
            				besteldProduct.getProduct().getProductSoort().getNaam(), 
            				besteldProduct.getAantal()); 
            				
            		ObjectMessage message = session.createObjectMessage(b);
                    producer.send(message);
                    
                    System.out.println("Bestelling: " + bestelling.getId() +" - " +
            				besteldProduct.getProduct().getNaam()  +" - " + 
            				besteldProduct.getProduct().getProductSoort().getNaam()  +" - " + 
            				besteldProduct.getAantal());
        		}

                connection.close();
                
			} catch (JMSException e) {
				e.printStackTrace();
			}   
		
			System.out.println("Bestelling verstuurt!");
	}
	
}
